import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Space, Radio, Select } from 'antd'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import PayModal from '@components/PayManage/PayModal'
import Detail from '@components/PayManage/Detail'
import { requestFiles } from '@js/request'
import { awaitWrap, formatCaseDataLicense } from '@js/tool'
import CaseNoRender from '@components/CaseNoRender'

const { Item } = Form
const { Option } = Select

const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      sorter: true,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicant_name',
      key: 'applicant_name',
      width: '15%'
    },
    {
      title: '被申请人',
      dataIndex: 'respondent_name',
      key: 'respondent_name',
      width: '15%'
    },
    {
      title: '支付类型',
      dataIndex: 'bill_type',
      key: 'bill_type'
    },
    {
      title: '费用',
      dataIndex: 'amount',
      key: 'amount',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '支付金额',
      dataIndex: 'pay_amount',
      key: 'pay_amount',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '生成时间',
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      sorter: true,
      render: v => {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD')
        }
      }
    },
    {
      title: '交费类型',
      dataIndex: 'type',
      key: 'type'
    },
    {
      title: '经办人',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      render: (value, line) => {
        return (
          <Space size='middle'>
            {
              line.status === '完成' ? (
                <span className={style['operate-btn']} onClick={() => this.setState({ billData: line, detailVisible: true })}>详情</span>
              ) : null
            }
            {
              line.status !== '完成' ? (
                <span className={style['operate-btn']} onClick={() => this.completeHandle(line)}>确认交费</span>
              ) : null
            }
            {line.documentid ? (
              <span className={style['operate-btn']} onClick={() => this.$readerPdf(`${line.acceptno_desc}交费单`, line.documentid, line.caseid)}>交费单</span>
            ) : null}
          </Space>
        )
      }
    }
  ]
}

class PayManage extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '未交费',
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    detailVisible: false,
    updateVisible: false,
    caseDetail: null,
    billData: null,
    dictionaries: {}
  }

  formRef = React.createRef()

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '交费单类型'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, status, orderField, order } = this.state
    const { current, pageSize } = pagination
    const condition = []
    const params = {
      current,
      page_size: pageSize
    }
    if (form.caseno) {
      condition.push({ k: 'acceptno_desc|caseno_desc', o: 'like', v: `%${form.caseno}%` })
    }
    if (form.applicant_name) {
      condition.push({ k: 'applicant_name', o: 'like', v: `%${form.applicant_name}%` })
    }
    if (form.bill_type) {
      condition.push({ k: 'b.type', o: '=', v: form.bill_type })
    }
    if (status === '未交费') {
      condition.push({ k: 'b.status', o: '=', v: '进行中' })
    } else {
      condition.push({ k: 'status', o: 'not in', v: '未提交,已提交,收案' })
    }
    if (status === '已交费') {
      params.ispay_type = '交费'
    }
    if (orderField && order) {
      params.order = order === 'ascend' ? 'asc' : 'desc'
      params.order_field = orderField
    }
    params.condition = JSON.stringify(condition)
    this.setState({ loading: true })
    this.$get('/api/xapc/bill', params).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    let field = sorter.field
    if (field === 'caseno_desc') {
      field = 'c.caseno_desc'
    } else if (field === 'pay_datetime') {
      field = 'p.pay_datetime'
    }
    this.setState({
      orderField: field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 完善信息按钮回调
  completeHandle (l) {
    const hide = message.loading('加载中', 120)
    this.$get(`/api/xapc/case/${l.caseid}`)
      .then(res => {
        hide()
        if (res.status === 1) {
          formatCaseDataLicense(res.data)
          this.setState({
            updateVisible: true,
            caseDetail: res.data,
            billData: l
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 完善信息请求
  async completeRequest (data) {
    const hide = message.loading('提交中', 120)
    const billid = data.id
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const [e, d] = await awaitWrap(requestFiles(file))
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    delete data.file
    delete data.id
    data.pay_datetime = Math.floor(data.pay_datetime.valueOf() / 1000)
    data.fileid = fileid
    this.setState({
      loading: true
    })
    this.$put('/api/xapc/pay', {
      ...data,
      caseid: this.state.caseDetail.id,
      pay_type: '线下',
      billid
    })
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getTableData()
          this.setState({
            updateVisible: false,
            caseDetail: null,
            billData: null
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => {
        hide()
      })
  }

  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  componentDidMount () {
    this.getDictionary()
    this.getTableData()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    const typeList = this.state.dictionaries['交费单类型'] || []
    return (
      <div className={style.container}>
        <PayModal visible={this.state.updateVisible} billData={this.state.billData} caseDetail={this.state.caseDetail} hide={() => this.setState({ updateVisible: false, billData: null, caseDetail: null })} onFinish={d => this.completeRequest(d)} />
        <Detail visible={this.state.detailVisible} billData={this.state.billData} hide={() => this.setState({ detailVisible: false, billData: null })} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='申请人' name='applicant_name'>
                    <Input placeholder='请输入申请人' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item labelCol={{ flex: '100px' }} label='交费单类型' name='bill_type'>
                    <Select placeholder='请选择交费单类型'>
                      {typeList.map(li => (
                        <Option key={li.title} value={li.value}>{li.title}</Option>
                      ))}
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-btns-line']}>
          <div className={style['table-tabs-container']}>
            <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
              <Radio.Button value='未交费'>未交费</Radio.Button>
              <Radio.Button value='已交费'>已交费</Radio.Button>
            </Radio.Group>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(PayManage)
